#include <iostream>
#include <sys/socket.h>
#include <unistd.h>
#include <string>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
using namespace std;

class Tcp_server
{
public:
    Tcp_server(int port)
        :_sockfd(-1)
        ,_port(port)
    {}


    void Init_Tcp()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if(_sockfd < 0)
        {
            cerr << "create socket fail!" << _sockfd << endl;
            exit(2);
        }
        cout << "create socket success!" << endl;

        struct sockaddr_in local;
        memset(&local, '\0', sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        if(bind(_sockfd, (struct sockaddr*)&local, sizeof(local)) < 0)
        {
            cerr << "bind error!" << endl;
            exit(3);
        }
        cout << "bind success!" << endl;
#define BACKLOG 5
        if(listen(_sockfd, BACKLOG) <  0)
        {
            cerr << "listen error!" << endl;
            exit(4);
        }
        cout << "listen success!" << endl;

    }

    void Start()
    {
        for(;;)
        {
            sockaddr_in peer;
            memset(&peer, '\0', sizeof(peer));
            socklen_t len = sizeof(peer);
            if(accept(_sockfd, (struct sockaddr*)&peer, &len) < 0)
            {
                cerr << "accept fail! continue!" << endl;
                continue;
            }
            string client_ip = inet_ntoa(peer.sin_addr);
            int client_port = ntohs(peer.sin_port);
            cout << "client ip: " << client_ip << "client port: " << client_port << endl;

            Service(_sockfd, client_ip, client_port);
        }
    }

    void Service(int sock, string client_ip, int client_port)
    {
        char buff[1024];
        while(true)
        {
            ssize_t ret = read(sock, buff, sizeof(buff)-1);
            if(ret > 0)
            {
                buff[ret] = '\0';
                cout << "get a new link-> " << sock << ":" << client_ip << ":" << client_port << endl;
                write(sock, buff, ret);
            }
            else if(ret == 0)
            {
                cout << client_ip << ":" << client_port << endl;
                break;
            }
            else
            {
                cerr << "sock error!" << endl;
                break;
            }
        }
    }

    ~Tcp_server()
    {
        if(_sockfd > 0)
            close(_sockfd);
    }
private:
    int _sockfd;
    int _port;
};

int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        cerr << "参数不完整请重新输入!" << endl;
        exit(1);
    }
    int port = atoi(argv[1]);
    Tcp_server* svr = new Tcp_server(port);
    svr->Init_Tcp();
    svr->Start();
    return 0;
}